<template>
  <div class="content">
    <e-heading v-if="list.length > 0" grade="1">添加报名成员</e-heading>
    <div class="memberStyle">
      <div v-if="list.length > 0">
        <!-- 网羽乒团体参赛成员列表 -->
        <el-table
          :data="list"
          style="width: 100%"
          v-if="teamMatchStyle.includes($route.query.matchtype)">
          <el-table-column
            prop="groupTeamName"
            width="90">
            <template slot-scope="scope">
              {{scope.row.groupTeamName}}
            </template>
          </el-table-column>
          <el-table-column
            prop="commingName"
            label="成员姓名"
            width="160">
            <template slot-scope="scope">
              <div :style="{textIndent: scope.row.isCaptain === 1 ? '0':'16px'}"><i class="icon iconfont icon-duichang" v-if="scope.row.isCaptain === 1"></i>{{ scope.row.commingName }}</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="sex"
            label="性别"
            align="center"
            width="65">
            <template slot-scope="scope">
              {{scope.row.sex === 1 ? '男': scope.row.sex === 2 ? '女' : ''}}
            </template>
          </el-table-column>
          <el-table-column
            prop="idNo"
            label="证件号"
            align="center"
            width="225">
          </el-table-column>
          <el-table-column
            prop="linkPhone"
            label="联系电话"
            align="center"
            width="130">
          </el-table-column>
          <el-table-column
            label="操作"
            align="center">
            <template slot-scope="scope">
              <div v-if="!scope.row.linkPhone">
                <el-button type="primary" size="mini" @click="handleAdd(scope.$index, scope.row)">添加</el-button>
              </div>
              <div v-else>
                <el-button type="link" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button type="link" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                <el-button type="link" @click="hanldeCaptain(scope.$index, scope.row)" :disabled="scope.row.isCaptain === 1">标记队长</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!-- 其他赛制参赛成员列表 -->
        <el-table
          :data="list"
          tooltip-effect="dark"
          style="width: 100%"
          v-else>
          <el-table-column
            prop="commingName"
            label="成员姓名"
            width="180">
            <template slot-scope="scope">
              <div :style="{textIndent: scope.row.isCaptain === 1 ? '0':'16px'}"><i class="icon iconfont icon-duichang" v-if="scope.row.isCaptain === 1"></i>{{ scope.row.commingName }}</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="sex"
            label="性别"
            align="center"
            width="80">
            <template slot-scope="scope">
              {{scope.row.sex === 1 ? '男': scope.row.sex === 2 ? '女' : ''}}
            </template>
          </el-table-column>
          <el-table-column
            prop="idNo"
            width="230"
            label="证件号"
            align="center"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="linkPhone"
            label="联系电话"
            align="center"
            width="150">
          </el-table-column>
          <el-table-column
            label="操作"
            align="center">
            <template slot-scope="scope">
              <el-button type="link" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button type="link" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
              <el-button type="link" @click="hanldeCaptain(scope.$index, scope.row)" :disabled="scope.row.isCaptain === 1" v-if="isTeamMatch.includes(race_detail.joinRequire) || isTeamMatch.includes($route.query.matchtype)">标记队长</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="btn-wrapper center">
          <el-button  @click="handleCancel">取消</el-button>
          <el-button  @click="handleAdd" v-if="!teamMatchStyle.includes($route.query.matchtype)">继续添加</el-button>
          <el-button type="primary" @click="handleSubmit" :disabled="!isSubmit || this.list.length < race_detail.playerNumber || this.list.length < race_detail.minTeamMember || this.list.length < doubleDisabled">提交信息</el-button>
        </div>
      </div>
      <!-- 无赛事成员 -->
      <div v-else>
        <e-placeholder text="暂无赛事联系人，快去添加吧！" src="/static/images/match/nomatch.png">
          <el-button type="primary" slot="button" @click="handleAdd">添加报名者</el-button>
        </e-placeholder>
      </div>
    </div>
    <!-- 弹框增加或编辑成员 -->
    <add-member :isShow="isShow" :matchtypeStyle="race_detail.joinRequire" :ageInfo="{minAge: race_detail.minAge, maxAge: race_detail.maxAge}" :memberInfo="memberInfo" v-if="isClose" v-model="isClose" @success="handleSuccess" />
  </div>
</template>

<script>
import addMember from './components/AddMember'
import {mapGetters} from 'vuex'
import api from 'api/race'
export default {
  components: {
    addMember
  },
  computed: {
    ...mapGetters({
      race_detail: 'race_detail'
    }),
    doubleDisabled: {
      get () {
        return this.matchStyle.includes(this.race_detail.joinRequire) ? 2 : ''
      }
    }
  },
  data () {
    return {
      isShow: false,
      isClose: false,
      isCaptain: false,
      memberInfo: {},
      list: [],
      isEdit: false, // 是否编辑成员
      editIndex: '',
      matchStyle: [20006, 20008, 20010], // 网羽乒双人赛
      multiMatchStyle: [20012], // 跑步多人赛
      teamMatchStyle: ['300301', '300401', '300501'], // 网羽乒团体
      isTeamMatch: [20002, 20004, '300301', '300401', '300501', 20013],
      isTeamMatchStyle: [20002, 20004, 20012, 20013], // 足球团体，篮球团体，跑步多人，跑步团体设置上限人数提示
      isSubmit: false,
      captainIndex: ''
    }
  },
  mounted () {
    if (this.teamMatchStyle.includes(this.$route.query.matchtype)) {
      let matchItem = this.$route.query.matchOrder.split(',')
      let array = []
      matchItem.forEach((item, index) => {
        if (item.length === 1) {
          array.push({
            playNumber: index + 1,
            roundType: item,
            groupTeamName: `第${index + 1}场(${item === '1' ? '男单' : item === '2' ? '女单' : item === '11' ? '男双' : item === '22' ? '女双' : item === '12' ? '混双' : ''})`,
            commingName: '',
            sex: 3,
            idNo: '',
            linkPhone: ''
          })
        } else {
          array.push(
            {
              playNumber: index + 1,
              roundType: item,
              groupTeamName: `第${index + 1}场(${item === '1' ? '男单' : item === '2' ? '女单' : item === '11' ? '男双' : item === '22' ? '女双' : item === '12' ? '混双' : ''})`,
              commingName: '',
              sex: 3,
              idNo: '',
              linkPhone: ''
            },
            {
              playNumber: index + 1,
              roundType: item,
              groupTeamName: '',
              commingName: '',
              sex: 3,
              idNo: '',
              linkPhone: ''
            }
          )
        }
        this.list = array
      })
    }
  },
  watch: {
    list (value) {
      for (let item of value) {
        if (item.linkPhone === '') {
          this.isSubmit = false
          return false
        } else {
          this.isSubmit = true
        }
      }
    }
  },
  methods: {
    handleAdd (index, row) {
      if ((this.matchStyle.includes(this.race_detail.joinRequire) && this.list.length === 2) || (this.isTeamMatchStyle.includes(this.race_detail.joinRequire) && this.list.length === this.race_detail.maxTeamMember)) {
        let remindMsg = this.race_detail.joinRequire === 20002 || this.race_detail.joinRequire === 20004 ? `该赛事报名人数必须介于${this.race_detail.minTeamMember}到${this.race_detail.maxTeamMember}人之间` : '报名人数已经达到上限！'
        this.$confirm(remindMsg, '温馨提示', {
          confirmButtonText: '我知道了',
          showCancelButton: false,
          type: 'warning'
        }).then(() => {
          return false
        })
      } else {
        this.isEdit = false
        this.isShow = true
        this.isClose = true
        this.memberInfo = {}
        if (this.teamMatchStyle.includes(this.$route.query.matchtype)) {
          this.isEdit = true
          this.memberInfo = row
          this.editIndex = index
        }
      }
    },
    handleEdit (index, row) {
      this.memberInfo = row
      this.isShow = true
      this.isClose = true
      this.isEdit = true
      this.editIndex = index
    },
    handleDelete (index, row) {
      this.$confirm('确认删除？，删除后不可恢复！', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.list.filter((item, n) => {
          if (n === index) {
            if (this.teamMatchStyle.includes(this.$route.query.matchtype)) {
              let existRow = {
                playNumber: item.playNumber,
                roundType: item.roundType,
                groupTeamName: item.groupTeamName,
                isCaptain: 0,
                commingName: '',
                sex: 3,
                idNo: '',
                linkPhone: '',
                birthday: '',
                extFields: []
              }
              this.list.splice(n, 1, existRow)
            } else {
              this.list.splice(n, 1)
            }
          }
        })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        // console.log(err)
      })
    },
    handleCancel () {
      this.$confirm('确认离开？，离开后信息不保存！', '温馨提示', {
        type: 'warning'
      }).then(() => {
        history.back()
      }).catch(() => {})
    },
    handleSuccess (value) {
      let isExist = false // 列表中是否已存在该报名人员
      let errMsg = '该参赛者已存在列表中，不可再添加'
      if (this.isEdit) {
        for (let i = 0; i < this.list.length; i++) {
          if (i !== this.editIndex) {
            if (this.list[i].linkPhone === value.linkPhone || this.list[i].idNo === value.idNo) {
              isExist = true
              this.isShow = true
            }
          }
        }
        if (isExist) {
          this.$message.error(errMsg)
          return
        }
        this.isShow = false
        this.list.splice(this.editIndex, 1, value)
      } else {
        for (let j = 0; j < this.list.length; j++) {
          if (this.list[j].linkPhone === value.linkPhone || this.list[j].idNo === value.idNo) {
            isExist = true
            this.isShow = true
          }
        }
        if (isExist) {
          this.$message.error(errMsg)
          return
        }
        this.isShow = false
        this.list.push(value)
      }
    },
    hanldeCaptain (index, row) {
      for (let i = 0; i < this.list.length; i++) {
        if (i === index) {
          for (let j = 0; j < this.list.length; j++) {
            this.list[j].isCaptain = 0
          }
          this.list[i].isCaptain = 1
        }
      }
    },
    handleSubmit () {
      if (this.multiMatchStyle.includes(this.race_detail.joinRequire) || this.matchStyle.includes(this.race_detail.joinRequire)) {
        // for (let i = 0; i < this.list.length; i++) {
        //   if (this.list[i].isCaptain === 1) {
        //     this.captainIndex = i
        //   }
        // }
        // if (typeof (this.captainIndex) === 'string') { // 是否标记了队长
        //   this.$confirm('请先标记队长！', '温馨提示', {
        //     confirmButtonText: '我知道了',
        //     showCancelButton: false,
        //     type: 'warning'
        //   }).then(() => {
        //     return false
        //   })
        // } else {
        let listMatchSignData = this.list.map((item, index) => {
          return {
            birthday: new Date(item.birthday).getTime(),
            commingName: item.commingName,
            idNo: item.idNo,
            linkPhone: item.linkPhone,
            sex: item.sex,
            matchSignFieldReqs: item.extFields.length ? item.extFields.map(item => {
              return {
                fieldText: item.fieldText,
                fieldValue: item.valueText
              }
            }) : []
          }
        })
        let matchListData = Object.assign({matchId: this.$route.query.id, groupType: this.$route.query.groupType, listMatchSignDataReq: listMatchSignData})
        let matchData = Object.assign({matchId: this.$route.query.id, matchParticipantReq: matchListData, captainIndex: this.captainIndex})
        api.saveMultiMember(matchData, {context: this, successMsg: '添加成功'}).then(res => {
          this.$router.push({path: '/race/detail/player', query: {id: this.$route.query.id, matchId: this.$route.query.id, matchtype: this.$route.query.matchtype, cost: this.$route.query.cost, tasktype: this.$route.query.tasktype, isRun: this.$route.query.isRun, matchOrder: this.race_detail.matchOrder}})
        })
        // }
      } else {
        for (let i = 0; i < this.list.length; i++) {
          if (this.list[i].isCaptain === 1) {
            this.captainIndex = i
          }
        }
        if (typeof (this.captainIndex) === 'string') { // 是否标记了队长
          this.$confirm('请先标记队长！', '温馨提示', {
            confirmButtonText: '我知道了',
            showCancelButton: false,
            type: 'warning'
          }).then(() => {
            return false
          })
        } else {
          let listMatchSignData = this.list.map((item, index) => {
            return {
              playNumber: item.playNumber,
              birthday: new Date(item.birthday).getTime(),
              commingName: item.commingName,
              idNo: item.idNo,
              linkPhone: item.linkPhone,
              roundType: item.roundType,
              sex: item.sex,
              matchSignFieldReqs: item.extFields && item.extFields.length ? item.extFields.map(item => {
                return {
                  fieldText: item.fieldText,
                  fieldValue: item.valueText
                }
              }) : []
            }
          })
          let matchListData = Object.assign({matchId: this.$route.query.id, groupType: this.$route.query.groupType, listMatchSignDataReq: listMatchSignData})
          let matchData = Object.assign({matchId: this.$route.query.id, matchParticipantReq: matchListData, captainIndex: this.captainIndex})
          api.searchIsExistClub(matchData, {context: this, successMsg: '添加成功'}).then(res => {
            this.$router.push({path: '/race/detail/player/createClub', query: {id: this.$route.query.id, matchId: this.$route.query.id, matchtype: this.$route.query.matchtype, cost: this.$route.query.cost, tasktype: this.$route.query.tasktype, isRun: this.$route.query.isRun, clubList: res.data.list, matchData: matchData}})
          })
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.memberStyle {
  .icon-duichang {
    color: rgb(215, 23, 24);
  }
  .btn-wrapper {
    margin-top: 40px;
  }
}
</style>
